<template>
  <base-page-view class-name="page-container mine-page">
    <view>
      <view class="user-top-box" :style="{'padding-top': statusBarHeight + 'px'}">
        <view v-if="false" class="sign-row" :style="{'top': 12 + statusBarHeight + 'px'}">
          <view class="sign-button">
            <image class="sign-icon" :src="'/static/images/mine/icon_my_sign.png'" />
            签到领好礼
          </view>
          <view class="setting-button" @click="$navigateTo('/pagesMine/setting/index')">
            <image class="icon" :src="'/static/images/mine/icon_my_setting.png'" />
          </view>
        </view>
        <view v-if="user" class="vipCard">
          <view class="userImg" @click="$navigateTo('/pagesMaterial/user-center/index')">
            <!-- <image v-if="user.is_crown" class="crown_bg" src="/static/images/mine/crown_ico.png" /> -->
            <image v-if="user.is_crown" class="crown_bg2" src="/static/images/mine/crown_ico_bak.png" />
            <image class="user" :src="user.head_img || '/static/images/user_logout.png'" @error="onImageLoad(user)" />
            <view class="tagBox">
              <view :class="'userTag color' + user.current_member_card_type" :style="{'width': tagFold ? '0' : '100%'}">
                <view class="userTagTit">{{ getUserLevelName() }}</view>
              </view>
              <image class="userTagImg" :src="(`/static/images/mine/vip_level_${user.current_member_card_type || 0}.png`)" @click.stop.prevent="setTagFold()" />
            </view>
          </view>
          <view class="userMsg">
            <view class="column">
              <view class="column-row">
                <view class="nickNameTit">{{ user.nickname }}</view>
                <view v-if="user.user_mark&&user.user_mark.length>0" class="official">
                  <image v-for="(item,index) in user.user_mark" :key="index" :src="item" alt="" class="officialImg" />
                </view>
              </view>
              <view class="inviteCodeView">
                邀请码:{{ user.invite_code }}
                <view class="copyBtn" @click="handleCopy(user.invite_code)">复制</view>
              </view>
              <!-- <view class="inviteCodeView">{{ '邀请人' }}:{{ user.referral_code ? userRerralCode : '无' }}</view> -->
            </view>
          </view>
          <view class="rightArror" @click.stop.prevent="$navigateTo('/pagesMaterial/user-center/index')">
            <image mode="aspectFit" :src="(`/static/images/mine/icon_my_more.png`)" />
          </view>
        </view>
      </view>
      <view class="to38Pack" :style="{'margin-bottom': user.current_member_card_type<2 ? '20rpx' : '80rpx' }" v-if="show_vip">
        <view class="normal" v-if="user.current_member_card_type===0">
          <url-image width="347" height="146" src="/static/images/member/mine/type1-1.png" @click="jump('vip')" class="img"/>
          <url-image width="347" height="146" src="/static/images/member/mine/type1-2.png" @click="jump('diamond')" />
        </view>
        <view class="normal" v-else-if="user.current_member_card_type===1">
          <url-image width="347" height="146" src="/static/images/member/mine/type2-1.png" @click="jump('diamond')" class="img"/>
          <url-image width="347" height="146" src="/static/images/member/mine/type2-2.png" @click="jump('box')" />
        </view>
        <view class="normal" v-else-if="user.current_member_card_type===2||user.current_member_card_type===3">
          <url-image width="347" height="146" src="/static/images/member/mine/type3-1.png" @click="jump('fx')" class="img"/>
          <url-image width="347" height="146" src="/static/images/member/mine/type3-2.png" @click="jump('box')" />
        </view>
        <!-- 旧版跳转 -->
        <!-- <template v-if="user.current_member_card_type < 2">
          <view class="normal">
            <b-image class="img" width="345" height="136" src="https://oss.bisinuolan.cn/default-1618558438910-ebcc3f92a33c47f394534bcdcef6230b.png" @click="toVipUrl" />
            <b-image width="345" height="136" src="https://oss.bisinuolan.cn/default-1618558468652-b291a0724e95423aba0590de3e6c2f4d.png" @click="jump('box')" />
          </view>
        </template>
        <template v-else>
          <view class="special">
            <b-image width="710" height="136" src="https://oss.bisinuolan.cn/default-1618558484429-965f8357f8384a45a618de9bada60b15.png" @click="jump('box')" />
          </view>
        </template> -->
      </view>
      <view v-if="localShow && setting.show_commission && price_obj &&show_vip" class="centerBox" :style="{ 'margin-top': user.current_member_card_type >1 ? '-60rpx' : '0' }" @click="$navigateTo('/pagesMine/earnings/index')">
        <view class="title">
          <view>我的收益(元)
          </view>
          <span> <image mode="aspectFit" src="/static/images/mine/icon_my_more.png" alt="" class="icon_my_more" /></span>
        </view>
        <view class="divW">
          <view class="divR">
            <view class="p1">{{ price_obj.bihs_valid_fee | formatMoney }}</view>
            <view class="p2">可提现</view>
          </view>
          <view class="divR">
            <view v-if="price_obj.earningmonth >= 0" class="p1">{{ price_obj.earningmonth | formatMoney }}</view>
            <view v-else class="p1 totalPriceRed">{{ Math.abs(price_obj.earningmonth) | formatMoney }}</view>
            <view class="p2">本月预估收益</view>
          </view>
          <!-- <view class="divR">
            <view v-if="earningData.totalCommission >= 0" class="p1">{{ earningData.totalCommission | formatMoney }}</view>
            <view v-else class="p1 totalPriceRed">{{ Math.abs(earningData.totalCommission) | formatMoney }}</view>
            <view class="p2">累计收益</view>
          </view> -->
          <view class="divR">
            <view v-if="price_obj.total_commission >= 0" class="p1">{{ price_obj.total_commission | formatMoney }}</view>
            <view v-else class="p1 totalPriceRed">{{ Math.abs(price_obj.total_commission) | formatMoney }}</view>
            <view class="p2">累计收益</view>
          </view>
        </view>
        <!-- <view v-if="user.current_member_card_type > 1" class="divW">
          <view class="divR">
            <view class="p1">{{ earningData.sangiftCommissionDay | formatMoney }}</view>
            <view class="p2">今日培养收益</view>
          </view>
          <view class="divR">
            <view class="p1">{{ earningData.earningday | formatMoney }}</view>
            <view class="p2">今日预估收益</view>
          </view>
          <view class="divR">
            <view class="p1">{{ earningData.todayOrderMoney| formatMoney }}</view>
            <view class="p2">今日销售额</view>
          </view>
        </view> -->
      </view>
      <!-- <view v-if="bxFans" class="centerBox" @click="$navigateTo('/pagesMine/bx-fans/index')"> -->
      <view v-if="bxFans&&show_vip" class="centerBox" @click="$navigateTo('/pagesMine/myBuddy/list')">
        <view class="title">
          <view>我的邀请(人)
          </view>
          <span> <image mode="aspectFit" src="/static/images/mine/icon_my_more.png" alt="" class="icon_my_more" /></span>
        </view>
        <view class="divW">
          <view class="divR">
            <!-- <view class="p1">{{ bxFans.inviteCount }}</view> -->
            <view class="p1">{{ bxFans.invite_total }}</view>
            <view class="p2">我的邀请</view>
          </view>
          <view class="divR">
            <!-- <view class="p1">{{ bxFans.childrenCount }}</view> -->
            <view class="p1">{{ bxFans.friends_total }}</view>
            <view class="p2">我的好友</view>
          </view>
          <!-- <view class="divR">
            <view class="p1">{{ bxFans.commonCount }}</view>
            <view class="p2">潜在VIP</view>
          </view>
          <view class="divR">
            <view class="p1">{{ bxFans.allVipMemberCount }}</view>
            <view class="p2">全部VIP</view>
          </view>
          <view class="divR">
            <view class="p1">{{ bxFans.childrenCount }}</view>
            <view class="p2">全部碧粉</view>
          </view> -->
        </view>
      </view>
      <view class="centerBox">
        <!-- <view class="title">
          <view>我的服务</view>
        </view> -->
        <view class="iconList">
          <view v-for="(item, index) in cardItem" :key="index" class="imgBox" @click="toUrl(item)">
            <image :src="item.image" class="iconImg" />
            <view class="desc">{{ item.title }}</view>
            <view v-if="item.rightCont" class="tips" :style="{'color': item.rightColor || ''}">{{ item.rightCont }}</view>
            <view v-if="item.rightNum" class="rightNum">{{ item.rightNum > 99 ? 99 : item.rightNum }}</view>
          </view>
        </view>
      </view>
      <view v-if="adList.length>0" class="adList">
        <base-swiper :swiper-list="adList" @itemClick="_toFunctionDetail">
        </base-swiper>
      </view>
      <view class="centerBox my-btn">
        <!-- <view class="title">我的功能</view> -->
        <view class="iconList">
          <block v-for="(item, index) in centerData" :key="index">
            <view v-if="!item.hide" class="imgBox" @click="toUrl(item)">
              <url-image :src="item.image" class="iconImg" />
              <view class="desc">{{ item.title }}</view>
              <view v-if="item.rightCont" class="tips" :style="{'color': item.rightColor || ''}">{{ item.rightCont }}</view>
              <view v-if="item.rightNum" class="rightNum">{{ item.rightNum }}</view>
              <view v-if="item.title === '绑定邀请' && showInvite" class="inviteTips" @click.prevent.stop="setInviteTips(item)">绑定邀请移到这里啦~ <image src="/static/images/icon/icon_close_grey.png" class="inviteIconClose" /></view>
            </view>
          </block>
        </view>
      </view>
    </view>
    <view v-if="showParentInvite" class="user-invite-info">
      <view class="mask"></view>
      <view class="parent-invite-box">
        <view class="bold title">温馨提示</view>
        <view>您已绑定邀请人: {{ user.parentNickname }}</view>
        <view>您的专属导师微信号</view>
        <view class="bold">{{ user.parentMobile }}</view>
        <view>关于省钱赚钱的问题, 请复制手机号去咨询吧~</view>
        <view>添加时请备注: 碧药会员</view>
        <view class="button" @click="handleCopy(user.parentMobile, '手机号复制成功')">复制手机号</view>
        <view class="button normal" @click="showParentInvite = false">关闭</view>
      </view>
    </view>
  </base-page-view>
</template>

<script>
import { mapActions } from 'vuex'
import baseSwiper from '@/components/base/base-swiper.vue'
import { setClipboardData } from '@/utils/tools'
import './index.scss'
import { toFunctionDetail, h5NavigateTo } from '@/utils/navigateTo.js'
export default {
  components: {
    baseSwiper
  },
  data() {
    return {
      user: '',
      excellentRate: {
        rateNum: 0,
        rateIndex: 0,
        rateList: [],
        ratePer: 0,
        rateState: false
      },
      statusBarHeight: 20,
      earningData: null, // 我的收益
      showParentInvite: false,
      tagFold: false,
      setting: {},
      bxFans: null, // 碧药粉丝
      cardItem: [
        {
          title: '我的订单',
          path: '/pagesMine/order/index',
          key: 'mine_order',
          image: '/static/images/mine/mine_order.png',
          rightCont: '',
          rightNum: 0
        },
        {
          title: '我的收藏',
          path: '/pagesMine/collection/index',
          key: 'mine_collection',
          image: '/static/images/mine/mine_collectTwo.png',
          rightCont: ''
        },
        {
          title: '优惠券',
          path: '/pagesMine/coupon/index',
          key: 'mine_coupons',
          image: '/static/images/mine/mine_couponTwo.png',
          rightCont: '',
          rightNum: 0 // 优惠券个数，必须第一位
        },
        {
          title: '购物车',
          path: '/pages/cart/index',
          key: 'mine_cart',
          image: '/static/images/mine/mine_cart.png',
          rightCont: '',
          rightNum: 0 // 优惠券个数，必须第一位
        }
      ],
      centerData: [
        {
          title: '会员中心',
          path: '/pagesMember/member/index',
          image: '/static/images/mine/member-center.png',
					hide: true,
        },
        {
          title: '个人主页',
          path: '/pagesMaterial/user-center/index',
          image: '/static/images/mine/my-center.png'
        },
        // {
        //   title: '派送福利',
        //   hide: true,
        //   path: '/pagesCommission/welfare/index',
        //   image: '/static/images/mine/icon_function_01_paisong.png'
        // },
        {
          title: '微信名片',
          path: '/pagesMine/wechat-card/index',
          image: '/static/images/mine/icon_function_02_wechat.png'
        },
        {
          title: '绑定邀请',
          path: '/pagesMine/bindCode/index',
          hasFun: true,
          image: '/static/images/mine/icon_function_03_bind.png'
        },
        {
          title: '直播选品',
          hide: true,
          path: '',
          image: '/static/images/mine/icon_function_04_live.png'
        },
        {
          title: '分享好友',
          path: '/pagesMine/invited/index',
          image: '/static/images/mine/icon_function_05_share.png'
        },
        {
          title: '意见反馈',
          path: '/pagesMine/feedback/index',
          image: '/static/images/mine/icon_function_06_yijian.png'
        },
        {
          title: '客服中心',
          path: '/pagesMine/service/index',
          image: '/static/images/mine/icon_function_07_help.png'
        },
        {
          title: '个人设置',
          path: '/pagesMine/setting/index',
          image: '/static/images/mine/icon_function_08_setting.png'
        }
      ],
      bindInput: '',
      showInviteLocal: '',
      adList: [],
      total_income: 0,
      total_earningmonth: 0,
      price_obj:"",//我的收益
			show_vip:false,
      localShow: true
    }
  },
  computed: {
    userRerralCode() {
      return this.user && this.user.referral_code && this.user.referral_code.length === 11 ? '碧药-' + this.user.referral_code.slice(this.user.referral_code.length - 4) : this.user.referral_code
    },
    showInvite() {
      return !this.user.referral_code && this.user.current_member_card_type !== 3 && !this.showInviteLocal
    }
  },
  async onShow() {
		const res = await this.$api.homeApi.getHomeDetail({
		  hideLoading: true
		})
		if(res&&res.data&&res.data.menuList){
			for (let s of res.data.menuList) {
				if(s.name=='会员升级'){
					this.show_vip=true;
				}
			}
		}
    this.initData();
    this.statusBarHeight = this.$statusBarHeight
    // #ifdef MP-WEIXIN
    uni.hideShareMenu()
    // #endif
  },
  onPullDownRefresh() {
    this.initData()
    uni.stopPullDownRefresh()
  },
  methods: {
    jump(type) {
      switch (type) {
        case 'box':
          // #ifdef H5
          if (this.$Bridge.isInApp) {
            this.$Bridge.callHandler({
              type: 'homeBox'
            })
          }
          // #endif
          uni.showToast({
            title: '仅APP支持查看，请下载APP',
            duration: 2000,
            icon: 'none'
          })
          break
        case 'vip':
          this.$navigateTo('/pagesMember/pay/index?type=vip')
          break;
        case 'diamond':
          this.$navigateTo('/pagesMember/pay/index?type=diamond')
          break;
        case 'fx':
          this.$navigateTo('/pagesMine/myBuddy/list')
          break;
        default:
          break;
      }
    },
    _toFunctionDetail(data) {
      toFunctionDetail(data.item, 'navigateTo', {
        preseat: data.item ? data.item.title : '',
        firstseat: '我的'
      })
    },
    setTagFold() {
      this.tagFold = !this.tagFold
      if (this.tagTimer) {
        clearTimeout(this.tagTimer)
      }
      this.tagTimer = setTimeout(() => {
        if (!this.tagFold) {
          this.tagFold = true
        }
      }, 3500)
    },
    showSharePop() {
      this.$refs.sharePop.show(this.shareOption)
    },
    async initData() {
      this.getCouponUnuse()
      this.setTagFold()
      await this.GetUserInfo().then(() => {
        this.user = this.$store.state.userInfo
        console.log("user,", this.user)
        this.showInviteLocal = uni.getStorageSync(this.user.mobile + 'showInvite')
        this.setting = {
          ...this.$store.state.setting
        }
        if (this.$store.state.setting && this.$store.state.setting.order_status_num) {
          let num = 0
          for (const key in this.$store.state.setting.order_status_num) {
            num = num + this.$store.state.setting.order_status_num[key]
          }
          this.cardItem[0].rightNum = num
        } else {
          this.cardItem[0].rightNum = 0
        }
				if(this.show_vip){
					this.getPromotionUrl();//获取收益
					this.getUserMember();//我的邀请
					this.centerData[0].hide=false;
				}
        // this.getLiveState()
        // this.setRedPoint()
        this.$nextTick(() => {
          if (this.$store.state.setting) {
            this.adList = []
            this.$store.state.setting.ad_list.forEach(element => {
              this.adList.push({ ...element, url: element.pic })
            })
          }
        })
      })
    },
    ...mapActions([
      'GetUserInfo'
    ]),
    getUserLevelName(current_member_card_type) {
      if (!this.user) {
        return '普通会员'
      }
      let state = '普通会员'
      switch (this.user.current_member_card_type) {
        case 0:
          state = '普通会员'
          break
        case 1:
          state = 'VIP会员'
          break
        case 2:
          state = '钻石会员'
          break
        case 3:
          state = '董事会员'
          break
        default:
          break
      }
      return state
    },
    toUrl(item) {
      if (item.hasFun) {
        if (item.title === '绑定邀请') {
          if (this.user.parentMobile) {
            this.showParentInvite = true
            return
          }
          if (this.user.current_member_card_type === 3) {
            uni.showToast({
              title: '您已是最高董事，无需绑定他人，感谢您的努力和支持',
              icon: 'none'
            })
            return
          }
        }
      }
      if (item.path) {
        this.$navigateTo(item.path)
      } else if (item.toUrl) {
        h5NavigateTo(item.toUrl)
      }
    },
    goBind() {
      this.$navigateTo('/pagesMine/bindCode/index')
    },
    orderClick(item) {
      this.$navigateTo(item.path)
    },
    handleCopy(invite_code, alertText) {
      this.showParentInvite = false
      setClipboardData({
        data: invite_code,
        success: () => {
          uni.showToast({
            title: alertText || '复制成功',
            icon: 'none'
          })
        }
      })
    },
    onImageLoad(item) {
      this.$set(item, 'head_img', 'https://asset.bisinuolan.cn/bixuan_uni/images/mine/touxiang.png')
    },
    // 优惠券个数
    async getCouponUnuse() {
      const res = await this.$api.couponApi.unusedCoupon({}, { showMessage: false })
      if (res.success) {
        this.cardItem[2].rightNum = res.data
      }
    },
    async getUserMember() {
      // const res = await this.$api.commissionApi.getBxFans({
      //   userId: this.user.uid,
      //   hideLoading: true
      // })
      // if (res.code === '000000') {
      //   this.bxFans = res.data
      // }
      this.$api.mineApi.myRewardInfo().then(res => {
        if (res.code == 0) {
          console.log(res.data)
          this.bxFans = res.data
        }
      })
      // setTimeout(function() {
      //   uni.stopPullDownRefresh()
      // }, 500)
    },
    // 获取碧药直播选品
    async getLiveState() {
      // this.centerData.filter(item => {
      //   return item.title === '派送福利'
      // })[0].hide = this.setting.show_region !== 1
      const result = await this.$api.excellentApi.getLiveState()
      if (result.success && result.data && result.data.anchor && result.data.selectionUrl) {
        const data = this.centerData.filter(item => {
          return item.title === '直播选品'
        })
        if (data.length) {
          data[0].hide = false
          data[0].toUrl = result.data.selectionUrl
        }
      }
    },
    toLocaltion(item) {
      h5NavigateTo(item.url)
    },
    async getPromotionUrl() {
      const res=await this.$api.boxApi.userPromotion();
      console.log(res);
      if(res.code===0){
        this.price_obj=res.data;
      }
    },
    setInviteTips(item) {
      uni.setStorage({
        key: this.user.mobile + 'showInvite',
        data: true
      })
      this.showInviteLocal = true
    },
    toVipUrl() {
      this.$trackSDK.track('bx.mine.button.click', '', {
        title: '立即开通'
      })
      this.$api.promotionApi.getVipUrl({
        userRole: this.user.current_member_card_type + ''
      }).then(res => {
        const info = res.data
        if (!info) {
          return
        }
        h5NavigateTo(info.vip_link)
      })
    }
  },
}
</script>
